<?php
declare (strict_types=1);

namespace app\user\service\teacher\admin;

use app\common\logic\category\admin\Category;
use app\common\service\BaseService;
use app\user\logic\teacher\admin\Teacher as TeacherLogic;
use app\user\logic\teacher\admin\TeacherLevel as TeacherLevelLogic;
use eduline\admin\libs\pageform\FormItem;
use eduline\admin\libs\pagelist\ListItem;
use eduline\admin\page\PageForm;
use eduline\admin\page\PageList;
use think\annotation\Inject;
use think\facade\Request;

/**
 * 讲师接口类
 */
class Teacher extends BaseService
{

    /**
     * @Inject()
     *
     * @var TeacherLogic
     */
    protected $teacherLogic;

    /**
     * @Inject()
     *
     * @var Category
     */
    protected $categoryLogic;

    /**
     * @Inject()
     *
     * @var TeacherLevelLogic
     */
    protected $teacherLevelLogic;

    /**
     * 讲师列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-16
     *
     * @return   [type]                         [description]
     */
    public function index()
    {
        // 搜索功能
        $map = [];
        Request::has('mhm_id', 'get', true) && $map[] = ['mhm_id', '=', Request::get('mhm_id/d')];
        $category = Request::get('category/d', 0);
        $category && $map[] = ['category', 'like', '%,' . $category . ',%'];
        if (Request::has('status', 'get', true) && Request::get('status/d', -1) !== -1) {
            $map[] = ['status', '=', Request::get('status/d')];
        } else {
            // 搜索功能
            $map[] = ['status', 'in', '0,1'];
        }

        $data = $this->teacherLogic->getList($map);

        $is_platform = request()->is_platform;
        // 定义字段
        $keyList = [
            'teacher_name'  => ListItem::make()->title('账号'),
            'school_name'   => ListItem::make()->title('关联机构')->visible($is_platform),
            'teacher_phone' => ListItem::make()->title('手机号'),
            'is_audit'      => ListItem::make('custom')->title('是否需要审核'),
            'status'        => ListItem::make('custom')->title('状态'),
            'update_time'   => ListItem::make()->title('更新时间'),
        ];

        // 讲师分类
        $category  = $this->categoryLogic->cascaderCate(0, 1);
        $searchKey = [
            'mhm_id'   => FormItem::make('searchSchool')->title(false)->visible($is_platform),
            'category' => FormItem::make('cascader')->title(false)->options($category)->placeholder('分类')->required(),
            'status'   => FormItem::make('select')->title(false)->placeholder('状态')->options([
                ['title' => '不限制', 'value' => -1],
                ['title' => '正常', 'value' => 1],
                ['title' => '禁止', 'value' => 0],
            ]),
        ];

        // 设置表单
        $list = app(PageList::class);
        // 搜索
        $list->searchKey = $searchKey;

        // 表单字段
        $list->pageKey = $keyList;

        $list->datas = $data;

        return $list->send();
    }

    /**
     * 创建讲师
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-16
     *
     * @return   [type]                         [description]
     */
    public function create()
    {
        if (Request::isPost()) {
            $data     = Request::post();
            $res      = $this->teacherLogic->createTeacher($data);
            $response = ['created' => 0];
            if ($res === 1) {
                // 创建了账号
                $response = ['created' => 1];
            }

            return $this->parseToData($response, 1, '新建成功');
        }
        // 设置表单
        $form = new PageForm();
        // 表单字段
        $form->pageKey = $this->keyListInit();

        $form->saveMethod  = 'POST';
        $form->savePostUrl = '/user/admin/teacher/create';

        return $form->send();
    }

    /**
     * 编辑讲师
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-16
     *
     * @return   [type]                         [description]
     */
    public function edit(int $id)
    {
        if (Request::isPut()) {
            $data = Request::put();
            $this->teacherLogic->editTeacher($id, $data);

            return $this->parseToData([], 1, '编辑成功');
        }

        $data        = $this->teacherLogic->with(['iDcardPositive', 'iDcardSide', 'certification', 'school'])->findOrFail($id);
        $data->cates = $data->fullcategorypath;
        // 创建课程界面配置
        $keyList = $this->keyListInit(false, $data->getAttr('mhm_id'));
        // 设置表单
        $form = new PageForm();
        // 表单字段
        $form->datas       = $data;
        $form->pageKey     = $keyList;
        $form->saveMethod  = 'PUT';
        $form->savePostUrl = '/user/admin/teacher/' . $id . '/edit';

        return $form->send();
    }

    /**
     * 课程界面配置
     * Author   亓官雨树<lucky.max@foxmail.com>
     * Date 2020-03-26
     */
    public function keyListInit($create = true, $mhmId = 0)
    {
        $enabled = $mhmId ? request()->mhm_id == $mhmId : true;
        // 讲师分类
        $category = $this->categoryLogic->cascaderCate(0, 1, $mhmId);
        // 机构等级
        $levels = $this->teacherLevelLogic->getSelectOptions($mhmId);
        // 定义字段
        $keyList = [
            // 'mhm_id'          => FormItem::make('searchSchool')->title('机构')->required()->visible($is_platform),
            'cates'           => FormItem::make('cascader')->title('分类')->options($category)->multiple(true)->required()->disabled(!$enabled),
            'level_id'        => FormItem::make('select')->title('等级')->options($levels)->required()->disabled(!$enabled),
            'user_phone'      => FormItem::make()->title('关联学员')->placeholder('输入学员手机号')->required()->help('手机号未注册学员时,会自动注册成为学员')->visible($create),
            'is_audit'        => FormItem::make('slideSwitch')->title('是否需要审核')->activeValue(1)->inactiveValue(0)->help('开启后，讲师上传的点播课程资源将需要审核'),
            // 'best_sort'       => FormItem::make('inputNumber')->title('排序值'),
            'info'            => FormItem::make('editor')->title('详细介绍'),
            'IDcard'          => FormItem::make()->title('身份证号码'),
            'IDcard_positive' => FormItem::make('custom')->title('身份证正面')->help('有头像的一面为正面'),
            'IDcard_side'     => FormItem::make('custom')->title('身份证反面')->help('有国徽的一面为反面'),
            'certification'   => FormItem::make('custom')->title('讲师资格证'),
            // 'status'          => FormItem::make('slideSwitch')->title('状态')->activeValue(1)->inactiveValue(0)->visible(!$create),
        ];

        return $keyList;
    }

    /**
     * 编辑字段
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/9/28
     *
     * @param int $id
     * @param     $field
     * @return \think\Response
     */
    public function editField(int $id, $field)
    {
        $value   = Request::put($field);
        $teacher = $this->teacherLogic->editField($id, $field, $value);

        return $this->parseToData($teacher, 1, '更新成功');
    }

    /**
     * 删除--软删除
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-29
     *
     * @param int $id [description]
     * @return   [type]                             [description]
     */
    public function delete(int $id)
    {
        $this->teacherLogic->deleteTeacher($id);

        return $this->parseToData([], 1, '删除成功');
    }

    /**
     * 待审核
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-05-29
     *
     * @return   [type]                         [description]
     */
    public function waiting()
    {
        $map  = [];
        $data = $this->teacherLogic->getWaitingList($map);
        // 定义字段
        $keyList = [
            'teacher_name'  => ListItem::make()->title('关联学员'),
            'teacher_phone' => ListItem::make()->title('申请人手机号'),
            'from_text'     => ListItem::make()->title('申请来源'),
            'create_time'   => ListItem::make()->title('申请时间'),
        ];

        // 设置表单
        $list = app(PageList::class);
        // 表单字段
        $list->pageKey = $keyList;
        $list->datas   = $data;

        return $list->send();
    }

    /**
     * 审核
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-03
     *
     * @return   [type]                         [description]
     */
    public function examine(int $id)
    {
        if (Request::isPost()) {
            $data = Request::post();
            $this->teacherLogic->doExamine($id, $data);

            return $this->parseToData([], 1, '审核完成');
        }

        $data = $this->teacherLogic->with(['user', 'iDcardPositive', 'iDcardSide', 'certification'])->findOrFail($id);

        $data->cates = $this->categoryLogic->parseTitle($data->getAttr('fullcategorypath'));

        return $this->parseToData($data, 1);
    }

    /**
     * 搜索讲师
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-06
     *
     * @param string $keyword [description]
     * @return   [type]                                  [description]
     */
    public function search(string $keyword = '')
    {
        $map = [
            ['__TABLE__.status', '=', 1],
            ['__TABLE__.mhm_id', '=', Request::get('mhm_id/d', request()->user->mhm_id)],
        ];

        $list = $this->teacherLogic->getSearchList($keyword, 12, $map);

        return $this->parseToData($list, 1, '获取成功');

    }

    /**
     * 批量禁用
     *
     * @return \think\Response
     */
    public function disables()
    {
        $ids = Request::put('ids/a');
        $this->teacherLogic->batchUpdated($ids, 'status', 0);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 批量启用
     *
     * @return \think\Response
     */
    public function enables()
    {
        $ids = Request::put('ids/a');
        $this->teacherLogic->batchUpdated($ids, 'status', 1);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 批量删除
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2020/10/16
     *
     * @return \think\Response
     */
    public function deletes($ids)
    {
        $this->teacherLogic->deleteTeachers($ids);

        return $this->parseToData([], 1, '操作成功');
    }

    /**
     * 获取讲师列表
     *
     * @return \eduline\admin\page\interfaces\think\Response
     * @throws \think\db\exception\DbException
     */
    public function getTeacherList()
    {
        $map = [
            ['__TABLE__.status', '=', 1],
            ['__TABLE__.mhm_id', '=', Request::get('mhm_id/d', request()->user->mhm_id)],
        ];

        // 条件
        $category = Request::get('category/d', 0);
        $category && $map[] = ['__TABLE__.category', 'like', '%,' . $category . ',%'];

        $keyword = Request::get('title/s');

        // 数量
        $count = Request::get('count/d', 15);

        $data = $this->teacherLogic->getTeacherList($keyword, $count, $map);

        $list        = new PageList();
        $list->datas = $data;

        return $list->send();

    }

    /**
     * 获取讲师信息
     *
     * @return \think\Response
     */
    public function getTeachers()
    {
        /** @var array $ids */
        $ids = Request::get('ids/a');

        $datas = $this->teacherLogic->getTeachers($ids);

        return $this->parseToData($datas, 1, '获取成功');
    }
}
